$(function () {
    /*
        参数解释：
        title	标题
        url		请求的url
        id		需要操作的数据id
        w		弹出层宽度（缺省调默认值）
        h		弹出层高度（缺省调默认值）
    */
    /**
     *  @author yys
     *  Description:  分页table
     *  @date  10:56 2018-01-16
     */
    var $table = $("#table");
    var _table = $table.dataTable($.extend(true, {}, CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
        ajax: function (data, callback, settings) {
            //封装请求参数
            var param = userManage.getQueryCondition(data);
            $.ajax({
                type: "POST",
                url: "/role/selectRoleByPage",
                cache: false,  //禁用缓存
                data: param,    //传入已封装的参数
                dataType: "json",
                success: function (result) {
                    //异常判断与处理
                    if (result.errorCode) {
                        alert("查询失败");
                        return;
                    }
                    //封装返回数据
                    var returnData = {};
                    returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                    returnData.recordsTotal = result.total;//总记录数
                    returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
                    returnData.data = result.pageData;
                    //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                    //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                    callback(returnData);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("查询失败");
                }
            });
        },
        //绑定数据
        columns: [
            {
                data: "roleId",//字段名
                orderable: false,//禁用排序
                render: function (data, type, row, meta) {
                    return (data != null ? "<input type=\"checkbox\" name=\"checkRoleId\"  style=\"text-align: center\" value=" + data + "  name=\"\">" : "error");
                }
            },
            {
                data: "roleId",//角色ID
            },
            {
                data: "roleName",//角色名
            },
            {
                data: "remarks",//备注
            },
            {
                data: "createTime",//备注
            },
            {
                data: "available",//状态
                orderable: true,//禁用排序
                sClass: "td-status",
                render: function (data, type, row, meta) {
                    return (data == 1 ? " <span class=\"label label-success radius\">已启用</span>" : data == 0 ? "<span class=\"label radius\">已停用</span>" : "不可用");
                }
            },
            {
                data: "roleId",//字段名
                orderable: false,//禁用排序
                sClass: "td-manage",
                render: function (data, type, row, meta) {
                    return (row.available == "1"
                            ?
                            "<a  onClick=\"role_change_status(this," + row.roleId + ",'0')\"   style=\"text-decoration:none\" href=\"javascript:;\" title=\"禁用\"><i class=\"Hui-iconfont\">&#xe631;</i></a> \n" +
                            "<a onclick=\"role_edit('角色编辑','/role/updateRoleInfo.do?roleId=" + row.roleId + "'," + row.roleId + ",'800','500')\" title=\"编辑\" href=\"javascript:;\"  class=\"ml-5\" style=\"text-decoration:none\"><i class=\"Hui-iconfont\">&#xe6df;</i></a>\n" +
                            "<a onclick=\"role_del(this," + row.roleId + ")\" title=\"删除\" href=\"javascript:;\"  class=\"ml-5\" style=\"text-decoration:none\"><i class=\"Hui-iconfont\">&#xe6e2;</i></a>"
                            :
                            "<a  onClick=\"role_change_status(this," + row.roleId + ",'1')\"   style=\"text-decoration:none\" href=\"javascript:;\" title=\"启用\"><i class=\"Hui-iconfont\">&#xe631;</i></a> \n" +
                            "<a onclick=\"role_edit('角色编辑','/role/updateRoleInfo.do?roleId=" + row.roleId + "'," + row.roleId + ",'800','500')\" title=\"编辑\" href=\"javascript:;\"  class=\"ml-5\" style=\"text-decoration:none\"><i class=\"Hui-iconfont\">&#xe6df;</i></a>\n" +
                            "<a onclick=\"role_del(this," + row.roleId + ")\" title=\"删除\" href=\"javascript:;\"  class=\"ml-5\" style=\"text-decoration:none\"><i class=\"Hui-iconfont\">&#xe6e2;</i></a>"
                    );
                }
            }
        ]
    })).api();//此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象

    /**
     *  @author yys
     *  Description:  分页table
     *  @date  10:59 2018-01-16
     */
    $("#btn_select").click(function () {
        _table.draw();
    });
})
/**
 *  @author yys
 *  Description:  分页查询请求参数封装
 *  @date  11:11 2018-01-16
 */
var userManage = {
    getQueryCondition: function (data) {
        var param = {};
        //组装排序参数
        if (data.order && data.order.length && data.order[0]) {
            switch (data.order[0].column) {
                case 1:
                    param.orderColumn = "roleId";//
                    break;
                case 2:
                    param.orderColumn = "roleName";//
                    break;
                case 3:
                    param.orderColumn = "remarks";//
                    break;
                case 4:
                    param.orderColumn = "create_Time";//
                    break;
                case 5:
                    param.orderColumn = "available";//
                    break;
                default:
                    param.orderColumn = "roleId";//
                    break;
            }
            //排序方式asc或者desc
            param.orderDir = data.order[0].dir;
        }
        param.roleName = $("#roleName").val();//查询条件
        param.createTime = $("#startTime").val();
        param.remarks = $("#endTime").val();
        param.available = $("#selAvailable").val();
        //组装分页参数
        param.startIndex = data.start;
        param.pageSize = data.length;
        param.draw = data.draw;
        return param;
    }
};

/*管理员-停用*/
function role_change_status(obj, roleId, available) {
    var confimTxt = available == "1" ? "确认要启用吗？" : "确认要停用吗？";
    layer.confirm(confimTxt, function (index) {
        //此处请求后台程序，下方是成功后的前台处理……
        var params = {roleId: roleId, available: available};
        $.ajax({
            type: "POST",
            url: "/role/updateAvailable",
            data: params,
            dataType: "json",
            success: function (data) {
                var data = eval(data);
                if (data.success == true) {
                    layer.msg(data.msg, {icon: 6, time: 1000});
                    window.location.reload();
                } else if (data.success == false) {
                    layer.msg(data.msg, {icon: 5, time: 1000});
                } else {
                    layer.msg('系统出错!', {icon: 1, time: 1000});
                    return;
                }
            },
            error: function (data) {
                console.log(data);
            }
        })
    });
}

$("#btnExportRoles").click(function () {
    layer.msg("正在导出，请稍等", {icon: 0, time: 5000});
    var roleName = $("#roleName").val();//查询条件
    var createTime = $("#startTime").val();
    var remarks = $("#endTime").val();
    var available = $("#selAvailable").val();
    var url = "/role/exportRoles?roleName=" + roleName + "&createTime=" + createTime + "&remarks=" + remarks + "&available=" + available;
    window.location.href = url;
})

/*角色-删除-批量*/
function datadel() {
    var roleId = "";
    var ids = $('input[type=checkbox]:checked');
    // var ids = $('input[name="checkUserId"]');
    if (ids.length > 0) {
        for (var i = 0; i < ids.length; i++) {
            var id = ids[i];
            if (id.checked && roleId == "" && id.value != "") {
                roleId = id.value + ',';
            } else if (id.checked && roleId != "" && id.value != "") {
                roleId += id.value + ',';
            }
        }
        var params = {roleId: roleId};
        layer.confirm('确认要删除吗？', function (index) {
            $.ajax({
                method: "POST",
                url: "/role/deleteRoleByRoleId",
                dataType: "json",
                data: params,
                success: function (data) {
                    var data = eval(data);
                    if (data.success == true) {
                        layer.msg(data.msg, {icon: 1, time: 2000}, function () {
                            window.location.reload();
                        });
                    } else if (data.success == false) {
                        layer.msg(data.msg, {icon: 2, time: 4000});
                        return;
                    }
                },
                error: function (data) {
                    console.log(data.msg);
                },
            });
        });
    } else {
        layer.msg("请至少选中一行删除!", {icon: 5, time: 1000});
    }
}

/*角色-添加*/
function role_add(title, url, w, h) {
    layer_show(title, url, w, h);
}

/*角色-编辑*/
function role_edit(title, url, id, w, h) {
    layer_show(title, url, w, h);
}

/*-角色-删除*/
function role_del(obj, roleId) {
    var params = {roleId: roleId};
    layer.confirm('确认要删除吗？', function (index) {
        $.ajax({
            method: "POST",
            url: "/role/deleteRoleByRoleId.do",
            dataType: "json",
            data: params,
            success: function (data) {
                var data = eval(data);
                if (data.success == true) {
                    layer.msg(data.msg, {icon: 1, time: 2000}, function () {
                        window.location.reload();
                    });
                } else if (data.success == false) {
                    layer.msg(data.msg, {icon: 2, time: 4000});
                    return;
                }
            },
            error: function (data) {
                console.log(data.msg);
            },
        });
    });
}